<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,">





  <link rel="alternate" href="/atom.xml" title="DG" type="application/atom+xml">






<meta name="description" content="Day30多表查询：* 查询语法：     select         列名列表     from         表名列表     where.... * 准备sql     # 创建部门表     CREATE TABLE dept(         id INT PRIMARY KEY AUTO_INCREMENT,         NAME VARCHAR(20)     );">
<meta name="keywords" content="Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Day30_MySQL多表&amp;事务">
<meta property="og:url" content="http://zhaowenhao99.github.io/2019/10/17/Day30_MySQL多表-事务/index.html">
<meta property="og:site_name" content="DG">
<meta property="og:description" content="Day30多表查询：* 查询语法：     select         列名列表     from         表名列表     where.... * 准备sql     # 创建部门表     CREATE TABLE dept(         id INT PRIMARY KEY AUTO_INCREMENT,         NAME VARCHAR(20)     );">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-10-18T00:22:46.881Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Day30_MySQL多表&amp;事务">
<meta name="twitter:description" content="Day30多表查询：* 查询语法：     select         列名列表     from         表名列表     where.... * 准备sql     # 创建部门表     CREATE TABLE dept(         id INT PRIMARY KEY AUTO_INCREMENT,         NAME VARCHAR(20)     );">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://zhaowenhao99.github.io/2019/10/17/Day30_MySQL多表-事务/">





  <title>Day30_MySQL多表&事务 | DG</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://zhaowenhao99.github.io/" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">DG</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhaowenhao99.github.io/2019/10/17/Day30_MySQL多表-事务/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="大狗">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/icon.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="DG">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Day30_MySQL多表&事务</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-17T08:19:42+08:00">
                2019-10-17
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/学习/" itemprop="url" rel="index">
                    <span itemprop="name">学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
               <span title="字数统计">
                    3.4k 字 
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                    15 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Day30"><a href="#Day30" class="headerlink" title="Day30"></a>Day30</h1><h2 id="多表查询："><a href="#多表查询：" class="headerlink" title="多表查询："></a>多表查询：</h2><pre><code>* 查询语法：
    select
        列名列表
    from
        表名列表
    where....
* 准备sql
    # 创建部门表
    CREATE TABLE dept(
        id INT PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(20)
    );
    INSERT INTO dept (NAME) VALUES (&apos;开发部&apos;),(&apos;市场部&apos;),(&apos;财务部&apos;);
    # 创建员工表
    CREATE TABLE emp (
        id INT PRIMARY KEY AUTO_INCREMENT,
        NAME VARCHAR(10),
        gender CHAR(1), -- 性别
        salary DOUBLE, -- 工资
        join_date DATE, -- 入职日期
        dept_id INT,
        FOREIGN KEY (dept_id) REFERENCES dept(id) -- 外键，关联部门表(部门表的主键)
    );
    INSERT INTO emp(NAME,gender,salary,join_date,dept_id) VALUES(&apos;孙悟空&apos;,&apos;男&apos;,7200,&apos;2013-02-24&apos;,1);
    INSERT INTO emp(NAME,gender,salary,join_date,dept_id) VALUES(&apos;猪八戒&apos;,&apos;男&apos;,3600,&apos;2010-12-02&apos;,2);
    INSERT INTO emp(NAME,gender,salary,join_date,dept_id) VALUES(&apos;唐僧&apos;,&apos;男&apos;,9000,&apos;2008-08-08&apos;,2);
    INSERT INTO emp(NAME,gender,salary,join_date,dept_id) VALUES(&apos;白骨精&apos;,&apos;女&apos;,5000,&apos;2015-10-07&apos;,3);
    INSERT INTO emp(NAME,gender,salary,join_date,dept_id) VALUES(&apos;蜘蛛精&apos;,&apos;女&apos;,4500,&apos;2011-03-14&apos;,1);
* 笛卡尔积：
    * 有两个集合A,B .取这两个集合的所有组成情况。
    * 要完成多表查询，需要消除无用的数据
* 多表查询的分类：
    1. 内连接查询：
        1. 隐式内连接：使用where条件消除无用数据
            * 例子：
            -- 查询所有员工信息和对应的部门信息

            SELECT * FROM emp,dept WHERE emp.`dept_id` = dept.`id`;

            -- 查询员工表的名称，性别。部门表的名称
            SELECT emp.name,emp.gender,dept.name FROM emp,dept WHERE emp.`dept_id` = dept.`id`;

            SELECT 
                t1.name, -- 员工表的姓名
                t1.gender,-- 员工表的性别
                t2.name -- 部门表的名称
            FROM
                emp t1,
                dept t2
            WHERE 
                t1.`dept_id` = t2.`id`;
</code></pre><p>​<br>​            2. 显式内连接：<br>​                <em> 语法： select 字段列表 from 表名1 [inner] join 表名2 on 条件<br>​                </em> 例如：<br>​                    <em> SELECT </em> FROM emp INNER JOIN dept ON emp.<code>dept_id</code> = dept.<code>id</code>;<br>​                    <em> SELECT </em> FROM emp JOIN dept ON emp.<code>dept_id</code> = dept.<code>id</code>;<br>​    </p>
<pre><code>    3. 内连接查询：
        1. 从哪些表中查询数据
        2. 条件是什么
        3. 查询哪些字段
2. 外链接查询：
    1. 左外连接：
        * 语法：select 字段列表 from 表1 left [outer] join 表2 on 条件；
        * 查询的是左表所有数据以及其交集部分。
        * 例子：
            -- 查询所有员工信息，如果员工有部门，则查询部门名称，没有部门，则不显示部门名称
            SELECT     t1.*,t2.`name` FROM emp t1 LEFT JOIN dept t2 ON t1.`dept_id` = t2.`id`;
    2. 右外连接：
        * 语法：select 字段列表 from 表1 right [outer] join 表2 on 条件；
        * 查询的是右表所有数据以及其交集部分。
        * 例子：
            SELECT     * FROM dept t2 RIGHT JOIN emp t1 ON t1.`dept_id` = t2.`id`;
3. 子查询：
    * 概念：查询中嵌套查询，称嵌套查询为子查询。
        -- 查询工资最高的员工信息
        -- 1 查询最高的工资是多少 9000
        SELECT MAX(salary) FROM emp;

        -- 2 查询员工信息，并且工资等于9000的
        SELECT * FROM emp WHERE emp.`salary` = 9000;

        -- 一条sql就完成这个操作。子查询
        SELECT * FROM emp WHERE emp.`salary` = (SELECT MAX(salary) FROM emp);

    * 子查询不同情况
        1. 子查询的结果是单行单列的：
            * 子查询可以作为条件，使用运算符去判断。 运算符： &gt; &gt;= &lt; &lt;= =
            * 
            -- 查询员工工资小于平均工资的人
            SELECT * FROM emp WHERE emp.salary &lt; (SELECT AVG(salary) FROM emp);
        2. 子查询的结果是多行单列的：
            * 子查询可以作为条件，使用运算符in来判断
            -- 查询&apos;财务部&apos;和&apos;市场部&apos;所有的员工信息
            SELECT id FROM dept WHERE NAME = &apos;财务部&apos; OR NAME = &apos;市场部&apos;;
            SELECT * FROM emp WHERE dept_id = 3 OR dept_id = 2;
            -- 子查询
            SELECT * FROM emp WHERE dept_id IN (SELECT id FROM dept WHERE NAME = &apos;财务部&apos; OR NAME = &apos;市场部&apos;);

        3. 子查询的结果是多行多列的：
            * 子查询可以作为一张虚拟表参与查询
            -- 查询员工入职日期是2011-11-11日之后的员工信息和部门信息
            -- 子查询
            SELECT * FROM dept t1 ,(SELECT * FROM emp WHERE emp.`join_date` &gt; &apos;2011-11-11&apos;) t2
            WHERE t1.id = t2.dept_id;

            -- 普通内连接
            SELECT * FROM emp t1,dept t2 WHERE t1.`dept_id` = t2.`id` AND t1.`join_date` &gt;  &apos;2011-11-11&apos;

* 多表查询练习

        -- 部门表
        CREATE TABLE dept (
          id INT PRIMARY KEY PRIMARY KEY, -- 部门id
          dname VARCHAR(50), -- 部门名称
          loc VARCHAR(50) -- 部门所在地
        );

        -- 添加4个部门
        INSERT INTO dept(id,dname,loc) VALUES 
        (10,&apos;教研部&apos;,&apos;北京&apos;),
        (20,&apos;学工部&apos;,&apos;上海&apos;),
        (30,&apos;销售部&apos;,&apos;广州&apos;),
        (40,&apos;财务部&apos;,&apos;深圳&apos;);
</code></pre><p>​<br>​<br>​                – 职务表，职务名称，职务描述<br>​                CREATE TABLE job (<br>​                  id INT PRIMARY KEY,<br>​                  jname VARCHAR(20),<br>​                  description VARCHAR(50)<br>​                );<br>​<br>                – 添加4个职务<br>                INSERT INTO job (id, jname, description) VALUES<br>                (1, ‘董事长’, ‘管理整个公司，接单’),<br>                (2, ‘经理’, ‘管理部门员工’),<br>                (3, ‘销售员’, ‘向客人推销产品’),<br>                (4, ‘文员’, ‘使用办公软件’);</p>
<p>​<br>​<br>​                – 员工表<br>​                CREATE TABLE emp (<br>​                  id INT PRIMARY KEY, – 员工id<br>​                  ename VARCHAR(50), – 员工姓名<br>​                  job_id INT, – 职务id<br>​                  mgr INT , – 上级领导<br>​                  joindate DATE, – 入职日期<br>​                  salary DECIMAL(7,2), – 工资<br>​                  bonus DECIMAL(7,2), – 奖金<br>​                  dept_id INT, – 所在部门编号<br>​                  CONSTRAINT emp_jobid_ref_job_id_fk FOREIGN KEY (job_id) REFERENCES job (id),<br>​                  CONSTRAINT emp_deptid_ref_dept_id_fk FOREIGN KEY (dept_id) REFERENCES dept (id)<br>​                );<br>​<br>                – 添加员工<br>                INSERT INTO emp(id,ename,job_id,mgr,joindate,salary,bonus,dept_id) VALUES<br>                (1001,’孙悟空’,4,1004,’2000-12-17’,’8000.00’,NULL,20),<br>                (1002,’卢俊义’,3,1006,’2001-02-20’,’16000.00’,’3000.00’,30),<br>                (1003,’林冲’,3,1006,’2001-02-22’,’12500.00’,’5000.00’,30),<br>                (1004,’唐僧’,2,1009,’2001-04-02’,’29750.00’,NULL,20),<br>                (1005,’李逵’,4,1006,’2001-09-28’,’12500.00’,’14000.00’,30),<br>                (1006,’宋江’,2,1009,’2001-05-01’,’28500.00’,NULL,30),<br>                (1007,’刘备’,2,1009,’2001-09-01’,’24500.00’,NULL,10),<br>                (1008,’猪八戒’,4,1004,’2007-04-19’,’30000.00’,NULL,20),<br>                (1009,’罗贯中’,1,NULL,’2001-11-17’,’50000.00’,NULL,10),<br>                (1010,’吴用’,3,1006,’2001-09-08’,’15000.00’,’0.00’,30),<br>                (1011,’沙僧’,4,1004,’2007-05-23’,’11000.00’,NULL,20),<br>                (1012,’李逵’,4,1006,’2001-12-03’,’9500.00’,NULL,30),<br>                (1013,’小白龙’,4,1004,’2001-12-03’,’30000.00’,NULL,20),<br>                (1014,’关羽’,4,1007,’2002-01-23’,’13000.00’,NULL,10);</p>
<p>​<br>​<br>​                – 工资等级表<br>​                CREATE TABLE salarygrade (<br>​                  grade INT PRIMARY KEY,   – 级别<br>​                  losalary INT,  – 最低工资<br>​                  hisalary INT – 最高工资<br>​                );<br>​<br>                – 添加5个工资等级<br>                INSERT INTO salarygrade(grade,losalary,hisalary) VALUES<br>                (1,7000,12000),<br>                (2,12010,14000),<br>                (3,14010,20000),<br>                (4,20010,30000),<br>                (5,30010,99990);</p>
<pre><code>-- 需求：

-- 1.查询所有员工信息。查询员工编号，员工姓名，工资，职务名称，职务描述
/*
    分析：
        1.员工编号，员工姓名，工资，需要查询emp表  职务名称，职务描述 需要查询job表
        2.查询条件 emp.job_id = job.id

*/
SELECT 
    t1.`id`, -- 员工编号
    t1.`ename`, -- 员工姓名
    t1.`salary`,-- 工资
    t2.`jname`, -- 职务名称
    t2.`description` -- 职务描述
FROM 
    emp t1, job t2
WHERE 
    t1.`job_id` = t2.`id`;
</code></pre><p>​<br>​<br>​                – 2.查询员工编号，员工姓名，工资，职务名称，职务描述，部门名称，部门位置<br>​                /<em><br>​                    分析：<br>​                        1. 员工编号，员工姓名，工资 emp  职务名称，职务描述 job  部门名称，部门位置 dept<br>​                        2. 条件： emp.job_id = job.id and emp.dept_id = dept.id<br>​                </em>/<br>​<br>                SELECT<br>                    t1.<code>id</code>, – 员工编号<br>                    t1.<code>ename</code>, – 员工姓名<br>                    t1.<code>salary</code>,– 工资<br>                    t2.<code>jname</code>, – 职务名称<br>                    t2.<code>description</code>, – 职务描述<br>                    t3.<code>dname</code>, – 部门名称<br>                    t3.<code>loc</code> – 部门位置<br>                FROM<br>                    emp t1, job t2,dept t3<br>                WHERE<br>                    t1.<code>job_id</code> = t2.<code>id</code> AND t1.<code>dept_id</code> = t3.<code>id</code>;</p>
<pre><code>-- 3.查询员工姓名，工资，工资等级
/*
    分析：
        1.员工姓名，工资 emp  工资等级 salarygrade
        2.条件 emp.salary &gt;= salarygrade.losalary and emp.salary &lt;= salarygrade.hisalary
            emp.salary BETWEEN salarygrade.losalary and salarygrade.hisalary
*/
SELECT 
    t1.ename ,
    t1.`salary`,
    t2.*
FROM emp t1, salarygrade t2
WHERE t1.`salary` BETWEEN t2.`losalary` AND t2.`hisalary`;
</code></pre><p>​<br>​<br>​                – 4.查询员工姓名，工资，职务名称，职务描述，部门名称，部门位置，工资等级<br>​                /<em><br>​                    分析：<br>​                        1. 员工姓名，工资 emp ， 职务名称，职务描述 job 部门名称，部门位置，dept  工资等级 salarygrade<br>​                        2. 条件： emp.job_id = job.id and emp.dept_id = dept.id and emp.salary BETWEEN salarygrade.losalary and salarygrade.hisalary<br>​                            
                </em>/<br>                SELECT<br>                    t1.<code>ename</code>,<br>                    t1.<code>salary</code>,<br>                    t2.<code>jname</code>,<br>                    t2.<code>description</code>,<br>                    t3.<code>dname</code>,<br>                    t3.<code>loc</code>,<br>                    t4.<code>grade</code><br>                FROM<br>                    emp t1,job t2,dept t3,salarygrade t4<br>                WHERE<br>                    t1.<code>job_id</code> = t2.<code>id</code><br>                    AND t1.<code>dept_id</code> = t3.<code>id</code><br>                    AND t1.<code>salary</code> BETWEEN t4.<code>losalary</code> AND t4.<code>hisalary</code>;</p>
<p>​<br>​<br>​                – 5.查询出部门编号、部门名称、部门位置、部门人数<br>​<br>                /*<br>                    分析：<br>                        1.部门编号、部门名称、部门位置 dept 表。 部门人数 emp表<br>                        2.使用分组查询。按照emp.dept_id完成分组，查询count(id)<br>                        3.使用子查询将第2步的查询结果和dept表进行关联查询</p>
<pre><code>*/
SELECT 
    t1.`id`,t1.`dname`,t1.`loc` , t2.total
FROM 
    dept t1,
    (SELECT
        dept_id,COUNT(id) total
    FROM 
        emp
    GROUP BY dept_id) t2
WHERE t1.`id` = t2.dept_id;
</code></pre><p>​<br>​                – 6.查询所有员工的姓名及其直接上级的姓名,没有领导的员工也需要查询<br>​<br>                /*<br>                    分析：<br>                        1.姓名 emp， 直接上级的姓名 emp</p>
<pre><code>            * emp表的id 和 mgr 是自关联
        2.条件 emp.id = emp.mgr
        3.查询左表的所有数据，和 交集数据
            * 使用左外连接查询

*/
/*
select
    t1.ename,
    t1.mgr,
    t2.`id`,
    t2.ename
from emp t1, emp t2
where t1.mgr = t2.`id`;

*/

SELECT 
    t1.ename,
    t1.mgr,
    t2.`id`,
    t2.`ename`
FROM emp t1
LEFT JOIN emp t2
ON t1.`mgr` = t2.`id`;
</code></pre><h2 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h2><pre><code>1. 事务的基本介绍
    1. 概念：
        *  如果一个包含多个步骤的业务操作，被事务管理，那么这些操作要么同时成功，要么同时失败。

    2. 操作：
        1. 开启事务： start transaction;
        2. 回滚：rollback;
        3. 提交：commit;
    3. 例子：
        CREATE TABLE account (
            id INT PRIMARY KEY AUTO_INCREMENT,
            NAME VARCHAR(10),
            balance DOUBLE
        );
        -- 添加数据
        INSERT INTO account (NAME, balance) VALUES (&apos;zhangsan&apos;, 1000), (&apos;lisi&apos;, 1000);
</code></pre><p>​<br>​            SELECT * FROM account;<br>​            UPDATE account SET balance = 1000;<br>​            – 张三给李四转账 500 元<br>​<br>            – 0. 开启事务<br>            START TRANSACTION;<br>            – 1. 张三账户 -500</p>
<pre><code>        UPDATE account SET balance = balance - 500 WHERE NAME = &apos;zhangsan&apos;;
        -- 2. 李四账户 +500
        -- 出错了...
        UPDATE account SET balance = balance + 500 WHERE NAME = &apos;lisi&apos;;

        -- 发现执行没有问题，提交事务
        COMMIT;

        -- 发现出问题了，回滚事务
        ROLLBACK;
    4. MySQL数据库中事务默认自动提交

        * 事务提交的两种方式：
            * 自动提交：
                * mysql就是自动提交的
                * 一条DML(增删改)语句会自动提交一次事务。
            * 手动提交：
                * Oracle 数据库默认是手动提交事务
                * 需要先开启事务，再提交
        * 修改事务的默认提交方式：
            * 查看事务的默认提交方式：SELECT @@autocommit; -- 1 代表自动提交  0 代表手动提交
            * 修改默认提交方式： set @@autocommit = 0;


2. 事务的四大特征：
    1. 原子性：是不可分割的最小操作单位，要么同时成功，要么同时失败。
    2. 持久性：当事务提交或回滚后，数据库会持久化的保存数据。
    3. 隔离性：多个事务之间。相互独立。
    4. 一致性：事务操作前后，数据总量不变
3. 事务的隔离级别（了解）
    * 概念：多个事务之间隔离的，相互独立的。但是如果多个事务操作同一批数据，则会引发一些问题，设置不同的隔离级别就可以解决这些问题。
    * 存在问题：
        1. 脏读：一个事务，读取到另一个事务中没有提交的数据
        2. 不可重复读(虚读)：在同一个事务中，两次读取到的数据不一样。
        3. 幻读：一个事务操作(DML)数据表中所有记录，另一个事务添加了一条数据，则第一个事务查询不到自己的修改。
    * 隔离级别：
        1. read uncommitted：读未提交
            * 产生的问题：脏读、不可重复读、幻读
        2. read committed：读已提交 （Oracle）
            * 产生的问题：不可重复读、幻读
        3. repeatable read：可重复读 （MySQL默认）
            * 产生的问题：幻读
        4. serializable：串行化
            * 可以解决所有的问题

        * 注意：隔离级别从小到大安全性越来越高，但是效率越来越低
        * 数据库查询隔离级别：
            * select @@tx_isolation;
        * 数据库设置隔离级别：
            * set global transaction isolation level  级别字符串;

    * 演示：
        set global transaction isolation level read uncommitted;
        start transaction;
        -- 转账操作
        update account set balance = balance - 500 where id = 1;
        update account set balance = balance + 500 where id = 2;
</code></pre><h2 id="DCL："><a href="#DCL：" class="headerlink" title="DCL："></a>DCL：</h2><pre><code>* SQL分类：
    1. DDL：操作数据库和表
    2. DML：增删改表中数据
    3. DQL：查询表中数据
    4. DCL：管理用户，授权

* DBA：数据库管理员

* DCL：管理用户，授权
    1. 管理用户
        1. 添加用户：
            * 语法：CREATE USER &apos;用户名&apos;@&apos;主机名&apos; IDENTIFIED BY &apos;密码&apos;;
        2. 删除用户：
            * 语法：DROP USER &apos;用户名&apos;@&apos;主机名&apos;;
        3. 修改用户密码：

            UPDATE USER SET PASSWORD = PASSWORD(&apos;新密码&apos;) WHERE USER = &apos;用户名&apos;;
            UPDATE USER SET PASSWORD = PASSWORD(&apos;abc&apos;) WHERE USER = &apos;lisi&apos;;

            SET PASSWORD FOR &apos;用户名&apos;@&apos;主机名&apos; = PASSWORD(&apos;新密码&apos;);
            SET PASSWORD FOR &apos;root&apos;@&apos;localhost&apos; = PASSWORD(&apos;123&apos;);

            * mysql中忘记了root用户的密码？
                1. cmd -- &gt; net stop mysql 停止mysql服务
                    * 需要管理员运行该cmd

                2. 使用无验证方式启动mysql服务： mysqld --skip-grant-tables
                3. 打开新的cmd窗口,直接输入mysql命令，敲回车。就可以登录成功
                4. use mysql;
                5. update user set password = password(&apos;你的新密码&apos;) where user = &apos;root&apos;;
                6. 关闭两个窗口
                7. 打开任务管理器，手动结束mysqld.exe 的进程
                8. 启动mysql服务
                9. 使用新密码登录。
        4. 查询用户：
            -- 1. 切换到mysql数据库
            USE myql;
            -- 2. 查询user表
            SELECT * FROM USER;

            * 通配符： % 表示可以在任意主机使用用户登录数据库

    2. 权限管理：
        1. 查询权限：
            -- 查询权限
            SHOW GRANTS FOR &apos;用户名&apos;@&apos;主机名&apos;;
            SHOW GRANTS FOR &apos;lisi&apos;@&apos;%&apos;;

        2. 授予权限：
            -- 授予权限
            grant 权限列表 on 数据库名.表名 to &apos;用户名&apos;@&apos;主机名&apos;;
            -- 给张三用户授予所有权限，在任意数据库任意表上

            GRANT ALL ON *.* TO &apos;zhangsan&apos;@&apos;localhost&apos;;
        3. 撤销权限：
            -- 撤销权限：
            revoke 权限列表 on 数据库名.表名 from &apos;用户名&apos;@&apos;主机名&apos;;
            REVOKE UPDATE ON db3.`account` FROM &apos;lisi&apos;@&apos;%&apos;;
</code></pre>
      
    </div>

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"> <i class="fa fa-tag"></i> Java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/16/Day29_MySQL约束/" rel="next" title="MySQL约束">
                <i class="fa fa-chevron-left"></i> MySQL约束
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/10/18/Day31_JDBC/" rel="prev" title="Day31_JDBC">
                Day31_JDBC <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



<div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
</div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/icon.jpg" alt="大狗">
            
              <p class="site-author-name" itemprop="name">大狗</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">45</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zhaowenhao99" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://zhaowenhao99.github.io" title="大狗之家" target="_blank">大狗之家</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Day30"><span class="nav-number">1.</span> <span class="nav-text">Day30</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#多表查询："><span class="nav-number">1.1.</span> <span class="nav-text">多表查询：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事务"><span class="nav-number">1.2.</span> <span class="nav-text">事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DCL："><span class="nav-number">1.3.</span> <span class="nav-text">DCL：</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大狗</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">39.5k</span>
  
</div>


  <div class="powered-by">个人专属</div>



  <span class="post-meta-divider">|</span>



<div class="powered-by">
<span id="sitetime"></span>
<script language="javascript">
  function siteTime(){
    window.setTimeout("siteTime()", 1000);
    var seconds = 1000;
    var minutes = seconds * 60;
    var hours = minutes * 60;
    var days = hours * 24;
    var years = days * 365;
    var today = new Date();
    var todayYear = today.getFullYear();
    var todayMonth = today.getMonth()+1;
    var todayDate = today.getDate();
    var todayHour = today.getHours();
    var todayMinute = today.getMinutes();
    var todaySecond = today.getSeconds();
    /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
    year - 作为date对象的年份，为4位年份值
    month - 0-11之间的整数，做为date对象的月份
    day - 1-31之间的整数，做为date对象的天数
    hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
    minutes - 0-59之间的整数，做为date对象的分钟数
    seconds - 0-59之间的整数，做为date对象的秒数
    microseconds - 0-999之间的整数，做为date对象的毫秒数 */
    var t1 = Date.UTC(2019,04,5,15,00,00); //北京时间2018-2-13 00:00:00
    var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
    var diff = t2-t1;
    var diffYears = Math.floor(diff/years);
    var diffDays = Math.floor((diff/days)-diffYears*365);
    var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
    var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
    var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
    document.getElementById("sitetime").innerHTML=" 已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
  }/*因为建站时间还没有一年，就将之注释掉了。需要的可以取消*/
  siteTime();
</script>
</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false});</script></body>
<script type="text/javascript" src="/js/src/clicklove.js"></script>
</html>
